import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React, { useState } from 'react';

const getBase64 = (img: any, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

//上传之前 可以控制上传文件的大小
const beforeUpload = (file: any) => {
    console.log(file)
};

// 类型声明
type Iprops = {
    onUpload?: any,
    imgUrl?: string
}

const Uploader = (props: any) => {
    console.log(props);

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();

    let { onUpload } = props

    const handleChange = (info: any) => {
        console.log(props);


        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (info.file.status === 'done') {
            // console.log('info', info.file.response)
            setLoading(false)
            onUpload(info.file.response.headimgurl)

            //上传的预览
            getBase64(info.file.originFileObj, (url: any) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 2,
                }}
            >
                上传类目图片
            </div>
        </div>
    );
    return (
        <Upload
            name="headimgurl"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/api/students/uploadStuAvatar"
            beforeUpload={beforeUpload}
            onChange={handleChange}
        >
            {imageUrl ? (
                <img
                    src={imageUrl}
                    alt="avatar"
                    style={{
                        width: '100%',
                    }}
                />
            ) : (
                uploadButton
            )}
        </Upload>
    );
};

export default Uploader;